package com.glamour.hlcity.component.framework.obse;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Observable;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.glamour.hlcity.common.enums.ErrorCodeEnum;
import com.glamour.hlcity.component.framework.common.FrameworkException;
import com.glamour.hlcity.component.framework.common.NotifyEnum;
import com.glamour.hlcity.component.framework.common.NotifyObject;
import com.glamour.hlcity.component.log.util.LogTracker;

public abstract class AbstractObserver implements ObserverListener {

	private final static Log LOG=LogFactory.getLog(AbstractObserver.class);
	
	@Override
	public void update(Observable observable, Object obj) {
		if(obj instanceof NotifyObject){
			NotifyObject temp=(NotifyObject)obj;
			//如果该监听者监听该服务，则执行之
			if(this.isServing(temp.geNotifyEnum())){
				update(temp.geNotifyEnum(), observable, obj);
			}
			
		}else{
			LOG.error("提醒传递的参数有误");
			throw new FrameworkException(ErrorCodeEnum.SYS_ERROR, "提醒传递的参数有误");
		}
	}
	
	@Override
	public  Boolean isServing(NotifyEnum notify){
		Set<String> collection=listenCollection();
		if(collection==null){
			throw new FrameworkException(ErrorCodeEnum.SYS_ERROR,this.toString()+",listenCollection()未实现");
		}
		return collection.contains(notify.getCode());
	}
	
	/**
	 * 返回所有的监听事件
	 * @return
	 */
	public abstract Set<String> listenCollection();
	
	/**
	 * 事件方法触发
	 * @param event
	 * @param observable
	 * @param obj
	 */
	private void update(NotifyEnum event,Observable observable,Object obj){
		
		  Method method = null;
	        try {
	            method = this.getClass().getMethod(event.getCode(), NotifyObject.class);
	        } catch (Exception e) {
	            LOG.warn(LogTracker.getMessage("事件处理方法没有找到！eventName = ", event.getCode()), e);
	            return;
	        }
	        if (method != null && Modifier.isPublic(method.getModifiers())) {
	            try {
	                method.invoke(this, obj);
	            } catch (Exception e) {
	                LOG.error(LogTracker.getMessage("事件处理执行失败！eventName = ", event.getCode()), e);
	           
	            }
	        }
	}

}






